package com.oraycn.esbasic.tools.httpDownloader;

import android.os.Build;

import com.oraycn.esbasic.helpers.FileHelper;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL; 

public class HttpDownloader {

    private String url;
    private String fileSavePath;
    private Boolean stopped = true;
    private Boolean isPaused = false;

    private long fileSize=0;
    private HttpDownloaderState state;

    private IHttpDownloaderListener httpDownloaderListener;
    public void setHttpDownloaderListener(IHttpDownloaderListener listener)
    {
        this.httpDownloaderListener=listener;
    }

    private Object tag;

    public void setTag(Object _tag) {
        this.tag = _tag;
    }

    public Object getTag() {
        return this.tag;
    }

    public HttpDownloader(String _url,String _fileSavePath)
    {
        this.url=_url;
        this.fileSavePath=_fileSavePath;
    }

    public String getFileSavePath()
    {
        return this.fileSavePath;
    }
    public long getFileSize()
    {
        return this.fileSize;
    }
    public HttpDownloaderState getState()
    {
        return this.state;
    }
    public String getUrl(){return this.url;}

    public void startAsyn()
    {
        if (!this.stopped)
        {
            return;
        }
        new Thread() {
            @Override
            public void run() {
                downLoadThread();
                state = HttpDownloaderState.Running;
            }
        }.start();
    }

    public void stopAsyn()
    {
        if (this.stopped)
        {
            return;
        }
        this.stopped = true;
        this.state = HttpDownloaderState.Cancelled;
    }

    private FileOutputStream fos;
    private InputStream inputStream;
    public String DownLoad() throws IOException
    {
        this.stopped=false;
        String fileDir=FileHelper.getFileDirectory(this.fileSavePath);
        File dir=new File(fileDir);
        if(!dir.exists()) {
            dir.mkdirs();
        }
        File file = new File(this.fileSavePath);
        file.createNewFile();
        URL url = new URL(this.url);
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        //设置超时间为5秒 (5秒未连接上将报错)
        conn.setConnectTimeout(5*1000);

        //得到输入流
        InputStream inputStream = conn.getInputStream();
        //获取自己数组
        byte[] getData = readInputStream(inputStream);

        //文件保存位置
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(getData);
        if(fos!=null){
            fos.close();
        }
        if(inputStream!=null){
            inputStream.close();
        }
        return this.fileSavePath;
    }

    private void downLoadThread() {
        try {
            this.stopped=false;
            String fileDir=FileHelper.getFileDirectory(this.fileSavePath);
            File dir=new File(fileDir);
            if(!dir.exists()) {
                dir.mkdirs();
            }
            File file = new File(this.fileSavePath);
            file.createNewFile();

            URL url = new URL(this.url);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //设置超时间为5秒 (5秒未连接上将报错)
            conn.setConnectTimeout(5 * 1000);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                this.fileSize = conn.getContentLengthLong();
            } else {
                this.fileSize = conn.getContentLength();
            }
            //得到输入流
            inputStream = conn.getInputStream();
            if (this.httpDownloaderListener != null) {
                this.httpDownloaderListener.downloadStarted(this);
            }
            //获取自己数组
            byte[] getData = readInputStream(inputStream);
            if(this.fileSize>getData.length)
            {
                this.state = HttpDownloaderState.Cancelled;
                if (this.httpDownloaderListener != null) {
                    this.httpDownloaderListener.downloadDisruptted(this, "已取消");
                }
                return;
            }
            //文件保存位置
            fos = new FileOutputStream(file);
            fos.write(getData);
            this.state = HttpDownloaderState.Completed;
            if (this.httpDownloaderListener != null) {
                this.httpDownloaderListener.downloadCompleted(this);
            }
        } catch (Exception e) {
            e.printStackTrace();
            if (this.httpDownloaderListener != null) {
                this.httpDownloaderListener.downloadDisruptted(this, e.getMessage());
            }
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                    fos=null;
                }
                if (inputStream != null) {
                    inputStream.close();
                    inputStream=null;
                }
            } catch (Exception e) {
                if (this.httpDownloaderListener != null) {
                    this.httpDownloaderListener.downloadDisruptted(this, e.getMessage());
                }
            }
        }
    }

    /**
     * 从输入流中获取字节数组
     * @param inputStream
     * @return
     * @throws IOException
     */
    private  byte[] readInputStream(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int len = 0;
        long totalDownloadBytes = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while ((len = inputStream.read(buffer)) != -1&&!this.stopped) {
            bos.write(buffer, 0, len);
            totalDownloadBytes += len;
            if (this.httpDownloaderListener != null) {
                this.httpDownloaderListener.downloadProgress(this, this.fileSize, totalDownloadBytes);
            }
        }
        bos.close();
        return bos.toByteArray();
    }

}


